/*
 *  Copyright 2002 by Texas Instruments Incorporated.
 *  All rights reserved. Property of Texas Instruments Incorporated.
 *  Restricted rights to use, duplicate or disclose this code are
 *  granted through contract.
 *  
 */
/*
 *  ======== diff_ti_apply.c ========
 *  Implementation of the color diff operation. 
 */

#pragma CODE_SECTION(DIFF_TI_apply, ".text:apply")

#include <std.h>

#include "idiff.h"
#include "diff_ti.h"
#include "diff_ti_priv.h"

    
/*
 *  ======== DIFF_TI_apply ========
 * Function computes the difference between a reference frame
 * and the current frame. 
 */    
Void DIFF_TI_apply(IDIFF_Handle handle, unsigned char y[], 
                     unsigned char cr[], unsigned char cb[], 
                     unsigned char prevY[], unsigned char prevCr[], 
                     unsigned char prevCb[], Int lumaSize, Int chromaSize,
                     Int yValue, Int crValue, Int cbValue, Int procWidth)
{    
//	DIFF_TI_Obj *diff = (DIFF_TI_Obj *)handle;
	
	Int i;
	Int diffCount;
	Int CrCbIdx;
	
	diffCount = 0;
		
	for (i = 0; i < lumaSize; i++)
	{
		if (abs((y[i] - prevY[i])) >= YTHRESHOLD)
		{
			diffCount++;
		}
	}
	
	if (diffCount >= DIFFTHRESHOLD)
	{
		for (i = 0; i < lumaSize; i++)	//Only need to go through unequal pixels
		{
			Int offset;
			
			if (abs((y[i] - prevY[i])) >= YTHRESHOLD)
			{
				y[i] = yValue;

				//Find the (Cr,Cb) pair that corresponds to the Y value
				//Compute first line, then do middle block in groups of 2.
				//Finally, compute last line.  This is based on the assumption
				//that we are processing 8 lines at a time.  For more lines
				//simple extend the number of 'else if' statements
								
				offset = i;
			
				if ((i >= procWidth) && (i < 3*procWidth))		//Lines 1-2
				{
					offset = i-procWidth;
				}
				else if ((i >= 3*procWidth) && (i < 5*procWidth)) 	//Lines 3-4
				{
					offset = i-2*procWidth;
				}
				else if ((i >= 5*procWidth) && (i < 7*procWidth)) 	//Lines 5-6
				{
					offset = i-3*procWidth;
				}
				else if (i >= 7*procWidth)							//Line 7
				{
					offset = i-4*procWidth;
				}
				
				//Assign CrCbIdx based on even or odd
				if ((offset % 2) == 0)
					CrCbIdx = offset >> 1;
				else
					CrCbIdx = (offset-1) >> 1;
				
				//Check (Cr,Cb) values and change if appropriate
				if (abs(cr[CrCbIdx] - prevCr[CrCbIdx]) >= CRCBTHRESHOLD)
				{
					cr[CrCbIdx] = crValue;
				}
				
				if (abs(cr[CrCbIdx] - prevCr[CrCbIdx]) >= CRCBTHRESHOLD)
				{
					cb[CrCbIdx] = cbValue;
				}
			}
		}
	}
	
}


